// my/qrCode/qrCode.js
const call = require('../../utils/request.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image:"", //二维码地址链接
    hidden: true,
    code: "",
    title: "",
    imgs: "",
    imgUrl: "",
    sHeight:"",
    sWidth:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getQRCode();
  },

  //获取海报、二维码、屏幕宽高等资源
  getQRCode(){
    wx.showLoading({
      title: '加载中',
      mask:true
    })
    call.post("/api/user/share_qrcode").then(res=>{
      console.log("获取二维码",res)
      if(res.data && res.data.code == 0){
        this.setData({
          image:res.data.data
        })
        // 请求海报封面
        Promise.all([
          //下载海报背景图
          this.DownLoadPic("imgs",call.host+'/fengxiangtupian.png'),
          //下载二维码
          this.DownLoadPic("code",this.data.image),
          //获取设备的宽高，因为canvas中像素是px而不是rpx
          new Promise((resolve,reject)=>{
            wx.getSystemInfo({
              success: res=> {
                resolve(3)
                this.setData({
                  sHeight: res.windowHeight,//设计稿上面的宽高
                  sWidth: res.windowWidth
                })
              }
            })
          })
        ]).then(()=>{
          //生成canvas
          this.getPhone(this.data.code, this.data.imgs, this.data.sWidth, this.data.sHeight, 'shareImg', 'center', 'red','yellow',)
        })
      }
    })
  },

  //保存海报到手机相册
  save (){
    console.log(11111111)
    var that = this
    wx.saveImageToPhotosAlbum({
      filePath: that.data.imgurl,
      success(t) {
        wx.showModal({
          content: '图片已保存到相册',
          showCancel: false,
          confirmText: '好的',
          success: function (t) {
            if (t.confirm) {
              console.log('用户确定了');
              // that.setData({
              //   hidden: true
              // })
            }
          },
        })
      },
      fail: function (t) {
        console.log("失败", t);
        wx.getSetting({
          success: function (t) {
            t.authSetting["scope.writePhotosAlbum"] || (console.log("进入信息授权开关页面"),
            wx.openSetting({
              success: function (t) {
                console.log("openSetting success", t.authSetting);
              }
            }));
          }
        });
      }
  })},
  
  //生成海报
  getPhone(code, imgs, sWidth, sHeight, classNames, textStyle, successCallback, textcolor, codecolor ){
    let that = this;
      const variableNum =sWidth / 750;
      // console.log(sWidth,sHeight)
      const ctx = wx.createCanvasContext(classNames);
      //求二维码大小和位置偏移
      const qrWidth = (125*(sWidth-40))/400;//(sWidth-40)/3.2;
      const bPOsi = (409*(sHeight-40))/591;//1.364/(sHeight-40);
      // console.log(bPOsi)
      ctx.drawImage(imgs, 20, 20,sWidth-40, sHeight-40);  //绘制图片
      ctx.drawImage(code, sWidth/2-(qrWidth/2), bPOsi+20, qrWidth,qrWidth); //绘制二维码
      ctx.stroke()
      ctx.draw();
    setTimeout(function () {  //这里要加定时器，转成图片需要一定的时间，不然是不出来图片的哦
      // canvas画布转成图片
      var i = getCurrentPages(), a = i[i.length - 1];//获取当前引用该方法的data里面的值
      wx.canvasToTempFilePath({
        x: 0,
        y: 0,
        width: sWidth,
        height: sHeight,
        destWidth: sWidth,
        destHeight: sHeight,
        canvasId: classNames,
        fileType: 'png',  
        success: (res)=>{
          wx.hideLoading();
          console.log(res);
          that.setData({
            imgurl: res.tempFilePath,
            hidden: false
          })
        },
        fail: function () {
          console.log("保存失败......")
        }
      })
    }, 500)
  },

  //加载图片的promise
  DownLoadPic(key,url){
    return new Promise((resolve,reject)=>{
      wx.downloadFile({
        url: url,
        success: (res) => {
          resolve(res)
          this.setData({
            [`${key}`]: res.tempFilePath
          })
        }
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})